package com.qg.lizhanqi.videosquare.activity;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.alibaba.fastjson.JSON;
import com.qg.lizhanqi.videosquare.R;
import com.qg.lizhanqi.videosquare.adaputer.CommentsAdapter;
import com.qg.lizhanqi.videosquare.bean.Comments;
import com.qg.lizhanqi.videosquare.bean.VideoInfors;
import com.qg.lizhanqi.videosquare.uitlhelp.DividerItemDecoration;
import com.qg.lizhanqi.videosquare.uitlhelp.MyUtils;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.RequestQueue;
import com.yolanda.nohttp.rest.Response;
import com.yolanda.nohttp.rest.SimpleResponseListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.LinkedList;
import java.util.List;

public class VideoActivity extends AppCompatActivity implements View.OnClickListener {
    private AlertDialog builder;
    private Button btn_login_submit;
    private TextView tv_login_register;
    private VideoView videoView;
    private TextView tv_Video_Issuer;
    private TextView tv_Video_Date;
    private TextView tv_Video_ID;
    private static final String TAG = "VideoActivity";
    private final String url = "http://101.200.142.201:8080/VideoPlay/video";
    private final String path = "http://101.200.142.201:8080/VideoPlay/commentList";
    private final String loginpath = "http://101.200.142.201:8080/VideoPlay/login";

    private RecyclerView commentRecyclerView;
    private Button btn_Comment;
    private ImageButton imagbtn_full;
    private LinearLayout linearLayout;
    final String LOGININFO = "loginInfo";
    private SharedPreferences sharedPreferences;
    private View loginView;
    private EditText editText_login_pass;
    private EditText editText_login_phone;
    private RequestQueue requestQueues;
    private int pageSize=20;
    private int page=1;
    private MediaController mediaController;
    private VideoInfors.VideoListBean video;
    LinkedList<Comments.CommlistBean> listComments;
    CommentsAdapter commentsAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video);
        initView();
        video = (VideoInfors.VideoListBean) getIntent().getSerializableExtra("video");
        Log.i(TAG, "onCreate:video " + video);
        tv_Video_Issuer.setText(video.getUsername());
        tv_Video_Date.setText("发布时间：" + video.getVideotime());
        tv_Video_ID.setText("视频库ID" + video.getUserid());
        MediaController     mediaController =  new MediaController(this);
        videoView.setVideoURI(Uri.parse(url + video.getVideourl()));
        videoView.setMediaController(mediaController);
        videoView.requestFocus(); //播放窗口为当前窗口
        videoView.start();
        getComments(path,video.getVideoid(),page,pageSize,false);



    }
    @TargetApi(Build.VERSION_CODES.M)
    private void initView() {
        //第一步：创建Nohttp请求对列
        requestQueues = NoHttp.newRequestQueue();
        videoView = (VideoView) findViewById(R.id.videoView);
        //设置videoView宽高
        ViewGroup.LayoutParams layoutParams = videoView.getLayoutParams();
        layoutParams.height= MyUtils.GetScreenHeight(this)/3;
        layoutParams.width= MyUtils.GetScreenWidth(this);
        videoView.setLayoutParams(layoutParams);

        tv_Video_Issuer = (TextView) findViewById(R.id.tv_Video_Issuer);
        tv_Video_Date = (TextView) findViewById(R.id.tv_Video_Date);
        tv_Video_ID = (TextView) findViewById(R.id.tv_Video_ID);
        commentRecyclerView = (RecyclerView) findViewById(R.id.commentRecyclerView);
        commentRecyclerView.setOnClickListener(this);
        btn_Comment = (Button) findViewById(R.id.btn_Comment);
        btn_Comment.setOnClickListener(this);
        imagbtn_full = (ImageButton) findViewById(R.id.imagbtn_full);
        imagbtn_full.setOnClickListener(this);
        imagbtn_full.getLayoutParams().height = MyUtils.GetScreenWidth(this) /10;
        imagbtn_full.getLayoutParams().width = MyUtils.GetScreenWidth(this) /10;
        linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
        linearLayout.setOnClickListener(this);
        //设置布局格式
        commentRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        //添加分割线
        commentRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        commentRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                Log.i(TAG, "滑动中");
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                //可以得到当前RecyclerView中Item的总数目?
                int totalItemCount = layoutManager.getItemCount();
                //得到最后一个可见的Item的位置position
                int lastVisibleItem = layoutManager.findLastVisibleItemPosition();
                Log.i(TAG, "onScrolled:总数 " + totalItemCount + "可见：" + lastVisibleItem);
                if (totalItemCount == lastVisibleItem + 1) {
                    Log.i(TAG, "onScrollStateChanged: 加载新的");
                    getComments(path,video.getVideoid(),++page,pageSize,false);
                }
            }
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_Comment:
                if (isLogin()){
                    //跳转到评论
                    Intent intent = new Intent(this, CommentActivity.class);
                    videoView.getLayoutParams().height = MyUtils.GetScreenWidth(this) / 3;
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("video",video);
                    intent.putExtras(bundle);
                    startActivityForResult(intent,20);
                }else {
                    alterLoginDiarlog();
                }
                break;
            case R.id.imagbtn_full:
                Log.i(TAG, "onClick: 切换屏幕按钮");
                if (getRequestedOrientation()==ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE){//横屏
                    //强制竖屏
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                }else {
                    //强制横屏
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                }
                break;
            case R.id.btn_login_submit:
                login();
                break;
        }
    }
    /*判断是否登录过*/
    public  boolean isLogin() {
        if (sharedPreferences == null) {
            sharedPreferences =getSharedPreferences(LOGININFO, Context.MODE_PRIVATE);
        }
        boolean islogin = sharedPreferences.getBoolean("islogin", false);
        return islogin;
    }
    /*登陆结果*/
    public void result(String responseString){
        try {
            JSONObject responseJson = new JSONObject(responseString);
            String code = responseJson.getString("code");
            if(code.equals("00000")){
                     /*关闭窗口*/
                if (builder.isShowing()) {
                    builder.dismiss();
                }
                JSONObject userinfo = responseJson.getJSONObject("userinfo");
                String userid = userinfo.getString("userid");
                String username = userinfo.getString("username");
                String userphone = userinfo.getString("userphone");
                if (sharedPreferences == null) {
                    sharedPreferences = getSharedPreferences(LOGININFO, Context.MODE_PRIVATE);
                }
                /*保存登陆状态*/
                sharedPreferences.edit()
                        .putBoolean("islogin",true)
                        .putString("userid",userid)
                        .putString("username",username)
                        .putString("userphone",userphone)
                        .commit();
                //跳转到评论
                Intent intent = new Intent(this, CommentActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("video",video);
                intent.putExtras(bundle);
                startActivityForResult(intent,20);
                Toast.makeText(VideoActivity.this, "登陆成功", Toast.LENGTH_SHORT).show();
            }else if(code.equals("00010")){
                Toast.makeText(VideoActivity.this, "登陆失败！账号已存在", Toast.LENGTH_SHORT).show();
            }
            else if(code.equals("00020")){
                Toast.makeText(VideoActivity.this, "登陆失败！手机验证失败", Toast.LENGTH_SHORT).show();
            }
            else if(code.equals("00030")){
                Toast.makeText(VideoActivity.this, "登陆失败！请求方式错误", Toast.LENGTH_SHORT).show();
            }
            else if(code.equals("00040")){
                Toast.makeText(VideoActivity.this, "登陆失败！参数不能为空", Toast.LENGTH_SHORT).show();
            }
            else if(code.equals("00050")){
                Toast.makeText(VideoActivity.this, "登陆失败！账户密码错误！", Toast.LENGTH_SHORT).show();
            }
            else if(code.equals("00060")){
                Toast.makeText(VideoActivity.this, "登陆失败！Token过期！", Toast.LENGTH_SHORT).show();
            }
            else if(code.equals("00070")){
                Toast.makeText(VideoActivity.this, "登陆失败！未知的错误！", Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    //初始化登录窗口的控件
    private void logininitView() {
        editText_login_phone = (EditText) loginView.findViewById(R.id.editText_login_phone);
        editText_login_pass = (EditText) loginView.findViewById(R.id.editText_login_pass);
        btn_login_submit = (Button) loginView.findViewById(R.id.btn_login_submit);
        tv_login_register = (TextView) loginView.findViewById(R.id.tv_login_register);
        tv_login_register.setOnClickListener(this);
        btn_login_submit.setOnClickListener(this);
    }
    /*登录窗口*/
    public void alterLoginDiarlog() {
        if (loginView == null) {
            Log.i(TAG, "alterLoginDiarlog: 填充登陆窗口");
            loginView = View.inflate(this, R.layout.activity_login, null);
            logininitView();
        }
        if (builder == null) {
            Log.i(TAG, "alterLoginDiarlog: 创建登陆窗口");
            builder = new AlertDialog.Builder(this).create();
            builder.setView(loginView);
        }
        builder.show();
    }
    /*登录方法*/
    private void login() {
        String loginphone = editText_login_phone.getText().toString();
        String loginpass = editText_login_pass.getText().toString();
        if (TextUtils.isEmpty(loginphone)) {
            Toast.makeText(VideoActivity.this, "手机号不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(loginpass)) {
            Toast.makeText(VideoActivity.this, "密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (MyUtils.isuserPhoneNumber(loginpass)) {
            Toast.makeText(VideoActivity.this, "手机号格式错误！请检查", Toast.LENGTH_SHORT).show();
            return;
        }
        requsetJson(loginphone, loginpass);
    }
    /*使用notthp的Post请求*/
    private void requsetJson(String loginphone, String loginpass) {
        Log.i(TAG, "登陆用户: " + loginphone + "密码:" + loginpass);
        Request<JSONObject> jsonObjectRequest = NoHttp.createJsonObjectRequest(loginpath, RequestMethod.POST);
        jsonObjectRequest.add("userPhone", loginphone);
        jsonObjectRequest.add("userPassword", loginpass);
        requestQueues.add(266, jsonObjectRequest, new SimpleResponseListener<JSONObject>() {
            @Override
            public void onSucceed(int i, Response<JSONObject> response) {
                try {
                    Log.i(TAG, "onSucceed: " + response.responseMesage());//ok
                    JSONObject jsonObject = response.get();
                    Log.i(TAG, "onSucceed: 请求登录获得到了结果"+jsonObject.toString());
                    result(jsonObject.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailed(int i, String s, Object o, Exception e, int i1, long l) {
                Log.i(TAG, "onFailed: "+e.toString());
                Toast.makeText(VideoActivity.this, "onFailed：登陆失败请稍后再试", Toast.LENGTH_SHORT).show();
            }
        });
    }
    public void getComments(String path, final String videoid, int page, int pageSize, final boolean isRefresh) {
        Request<String> stringRequest = NoHttp.createStringRequest(path, RequestMethod.POST);
        stringRequest.add("videoid",videoid);
        stringRequest.add("page",page);
        stringRequest.add("pageSize",pageSize);
        requestQueues.add(999, stringRequest, new SimpleResponseListener<String>() {
            @Override
            public void onSucceed(int i, Response<String> response) {
               String result = response.get();
               Comments comments = JSON.parseObject(result, Comments.class);
               String code = comments.getCode();
               if (code.equals("00000")) {
                   List<Comments.CommlistBean> newCommList = comments.getCommlist();
                   if (listComments == null) {//判断添加到的list集合是否为空
                       listComments = new LinkedList<Comments.CommlistBean>();
                   }
                   for (Comments.CommlistBean nc : newCommList) {
                       String commentconent = nc.getCommentconent();
                       String commentuserid = nc.getCommentuserid();
                       boolean ishave = false;
                       for (Comments.CommlistBean cls : listComments) {
                           if (cls.getCommentuserid().equals(commentuserid) && cls.getCommentconent().equals(commentconent)) {
                               ishave = true;
                           }
                       }
                       if (!ishave) {
                           if (isRefresh) {
                               listComments.addFirst(nc);
                           } else {
                               listComments.addLast(nc);
                           }
                       }
                   }
                   if (listComments != null) {
                       if (commentsAdapter==null){
                            commentsAdapter =  new CommentsAdapter(VideoActivity.this, listComments);
                           commentRecyclerView.setAdapter(commentsAdapter);
                       }else {
                           commentsAdapter.notifyDataSetChanged();
                       }
                   }
               }
           }
            @Override
            public void onFailed(int i, String s, Object o, Exception e, int i1, long l) {
                Toast.makeText(VideoActivity.this, "获取评论失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
    //横屏切换的时候
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (getRequestedOrientation()==ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE){//横屏
            Log.i(TAG, "横屏理论高: "+MyUtils.GetScreenHeight(this)+"宽："+MyUtils.GetScreenWidth(this));
            //设置宽高
            ViewGroup.LayoutParams layoutParams = videoView.getLayoutParams();
            layoutParams.height= MyUtils.GetScreenHeight(this);
            layoutParams.width= MyUtils.GetScreenWidth(this);
            videoView.setLayoutParams(layoutParams);
            linearLayout.setVisibility(View.GONE);
            Log.i(TAG, "横屏实际高: "+MyUtils.GetScreenHeight(this)+"宽："+MyUtils.GetScreenWidth(this));
        }else {
            linearLayout.setVisibility(View.VISIBLE);
            Log.i(TAG, "竖屏理论高: "+MyUtils.GetScreenHeight(this)+"宽："+MyUtils.GetScreenWidth(this));
            //设置宽高
            ViewGroup.LayoutParams layoutParams = videoView.getLayoutParams();
            layoutParams.height= MyUtils.GetScreenHeight(this)/3;
            layoutParams.width= MyUtils.GetScreenWidth(this);
            videoView.setLayoutParams(layoutParams);
            Log.i(TAG, "竖屏实际高: "+MyUtils.GetScreenHeight(this)+"宽："+MyUtils.GetScreenWidth(this));
        }
    }
    /*评论完成后*/
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //刷新评论
        if(requestCode==20){
            getComments(path,video.getVideoid(),1,pageSize,true);
        }
    }
}
